package basic.study.algorithms.struct;

/**
 * @author Kevin
 * @date 2020/2/25 13:56
 */
public class GenericArray<T> {
    private int size;
    private T[] data;

    public GenericArray(int size) {
        data = (T[])new Object[size];
        size = size;
    }
    public GenericArray() {
        this(10);
    }
    public int count() {
        return size;
    }
    public int getCapacity() {
        return data.length;
    }
    public boolean isEnpty() {
        return size==0;
    }

    public void set(int index, T e) {
        checkIndex(index);
        data[index]  =e;
    }

    public T get(int index) {
        checkIndex(index);
        return data[index];
    }
    public boolean contain(T e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return true;
            }
        }
        return false;
    }
    public int find(T e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return i;
            }
        }
        return -1;
    }

    public void add(int index, T e) {
        checkIndexForAdd(index);
        if (size == data.length) {
            resize(2*data.length);
        }
        for (int i = size-1; i >= index; i++) {
            data[i+1] = data[i];
        }
        data[index] = e;
        size++;
    }
    //向数组头插入元素
    public void addFirst(T e) {
        add(0,e);
    }
    public void addLast(T e) {
        add(size, e);
    }
    public T remove(int index) {
        checkIndex(index);

        T ret = data[index];
        for (int i = index+1; i < size; i++) {
            data[i-1] = data[i];
        }
        size --;
        data[size] = null;

        //缩容
        if (size == data.length / 4 && data.length / 2 != 0) {
            resize(data.length / 2);
        }
        return ret;
    }
    // 删除第一个元素
    public T removeFirst() {
        return remove(0);
    }

    // 删除末尾元素
    public T removeLast() {
        return remove(size - 1);
    }
    public void removeElement(T e) {
        int index = find(e);
        if (index != -1) {
            remove(index);
        }
    }

    private void resize(int len) {
        T[] newData = (T[]) new Object[len];

        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }
        data = newData;
    }

    private void checkIndex(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("Add failed! Require index >=0 and index < size.");
        }
    }
    private void checkIndexForAdd(int index) {
        if (index < 0 || index >= size) {
            throw new IllegalArgumentException("remove failed! Require index >=0 and index <= size.");
        }
    }

}
